import React from "react";
import { UserAPI } from "../utils";
import { Prompt } from "../react-router";

class UserAdd extends React.Component {
  usernameRef = React.createRef();
  state = { isBlocking: false }; // 定义一个状态，是否跳转的状态
  handleSubmit = (event) => {
    event.preventDefault();
    this.setState(
      {
        isBlocking: false,
      },
      () => {
        let username = this.usernameRef.current.value;
        UserAPI.add({
          id: Date.now(),
          username,
        });
        this.props.history.push("/user/list");
      }
    );
  };
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <Prompt
          when={this.state.isBlocking}
          message={(location) => `请问要跳到${location.pathname}吗？`}
        />
        <input
          type="text"
          ref={this.usernameRef}
          onChange={(event) =>
            this.setState({ isBlocking: event.target.value.length > 0 })
          }
        />
        <input type="submit" />
      </form>
    );
  }
}
export default UserAdd;
